package com.example.tongyao.system.config;

import com.auth0.jwt.interfaces.Claim;
import com.example.tongyao.utils.token.TokenUtil;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * TongYao2.0 >>> 【com.example.tongyao.system.config】
 * JWT 拦截器
 *
 * @author: tongyao
 * @since: 2021-08-01 17:47
 */
public class JwtInterceptor implements HandlerInterceptor{

    @Resource
    private TokenUtil tokenUtil;

    @Resource
    private UserDetailsService userDetailsService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        // 从 http 请求头中取出 token
        String token = httpServletRequest.getHeader("access_token");

        //tonken验证
        if (token == null) {
            throw new RuntimeException("令牌为空！");
        }

        // 获取 token 中的账号数据

        Map<String, Claim> userData = tokenUtil.parsingToken(token);

        String userName = userData.get("userName").asString();
        httpServletRequest.setAttribute("userName",userName);

        UserDetails user = userDetailsService.loadUserByUsername(userName);
        if (user == null) {
            throw new RuntimeException("用户不存在！");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }




}
